﻿using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.ViewModels;
using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;

namespace AnesSystem.Old
{
    /// <summary>
    /// SysMainWin.xaml 的交互逻辑
    /// </summary>
    public partial class SysMainWin : BaseWindow
    {

        #region Variables

        private static SysMainWin _instance;
        private MainPageCommonViewModel _model;
        private Key downKey;
        ScaleTransform _viewScaleTransform;
        private bool isTip = false;

        #endregion

        #region Constructor

        public SysMainWin()
        {
            InitializeComponent();
            _model = MainPageCommonViewModel.Instance;
            this.DataContext = _model;
            _viewScaleTransform = new ScaleTransform();
            UdpMangager.Instance.ReceivedMsg += Instance_ReceivedMsg;
            MongoDBUtil.Instance.ConnectionChanged += Instance_ConnectionChanged;
            this.Closing += SysMainWin_Closing;
            this.Loaded += SysMainWin_Loaded;
        }

        #endregion

        #region Properties

        public static SysMainWin Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SysMainWin();
                }
                return _instance;
            }
        }

        #endregion

        #region Event

        #endregion

        #region Private Methods

        private void InitialOffLine()
        {
            if (OffLineManager.Instance.HasOffLineFiles())
            {
                if (MessageBoxCommon.ShowDialog("当前手术间有未上传的手术信息,是否上传到服务器?", MessageBoxCommon.OKCANCLE).Value == true)
                {
                    Task.Factory.StartNew(delegate
                    {
                        OffLineManager.Instance.UpLoadInfos();
                        MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                        Dispatcher.Invoke(delegate
                        {
                            //WaitCtrl.Instance.Close();
                        });
                    });
                    MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
                }
            }
        }

        #endregion

        #region Public/Protected Methods

        #endregion

        #region EventHandlers

        private void Instance_ConnectionChanged(object sender, MongoConnectionArgs e)
        {
            if (!e.ConnectionStatus)
            {
                if (MainPageCommonViewModel.Instance.WaitCtrlVisibility != Visibility.Visible)
                {
                    MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
                }
                MainPageCommonViewModel.Instance.IsShowTimeOutDialog = true;
                MainPageCommonViewModel.Instance.WaitMessage = "服务器连接断开，正在重新连接服务器，请稍后...";
            }
            else
            {
                if (MainPageCommonViewModel.Instance.WaitCtrlVisibility != Visibility.Collapsed && MainPageCommonViewModel.Instance.IsShowTimeOutDialog)
                {
                    MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                    MainPageCommonViewModel.Instance.IsShowTimeOutDialog = false;
                }
            }
        }


        private void SysMainWin_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                WindowStyle = WindowStyle.None;
                this.Left = 0;
                this.Top = 0;
                this.Height = SystemParameters.WorkArea.Height;
                this.Width = SystemParameters.WorkArea.Width;
                //MainPageCommonViewModel.Instance.ReMsg();
                MainPageCommonViewModel.Instance.NavigateTo("XuanZeShouShuCtrl", false);
                //InitialOffLine();
            }
            catch (Exception ex)
            {

            }
        }

        private void ZhangHaoButton_Clic(object sender, RoutedEventArgs e)
        {
            AccountUpDateCtrl retypesettingCtrl = new AccountUpDateCtrl();
            DrugAndEventWindow.Instance.Title = "编辑账户";
            DrugAndEventWindow.Instance.CusContent = retypesettingCtrl;
            DrugAndEventWindow.Instance.ShowDialog();
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainPageCommonViewModel.Instance.NavigateTo("AnesRecordCtrl", false);
        }

        private void SysMainWin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            FullWindow.Instance.Close();
            PreviewPrintWindow.Instance.Close();
            DrugAndEventWindow.Instance.Close();
            VitalSignCapture.Instance.StopCapture();
            this.Close();
        }

        private void btnMin_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void menuButton_Click(object sender, RoutedEventArgs e)
        {
            if (menuButton.IsChecked == true)
            {
                muneS.Width = new GridLength(1, GridUnitType.Pixel);
            }
            if (menuButton.IsChecked == false)
            {
                muneS.Width = new GridLength(205, GridUnitType.Pixel);
            }
        }

        private void Instance_ReceivedMsg(object sender, UdpMsgAnalysisArgs e)
        {
            return;
            //try
            //{
            //    if (HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_FYBJY))
            //    {
            //        return;
            //    }
            //    if (isTip) return;
            //    AnesSystemModifyInfoModel model = e.UdpMsgAnalysis.CustomContent.JsonToObject<AnesSystemModifyInfoModel>();
            //    PatientLinkModel pm = null;
            //    if (!string.IsNullOrEmpty(model.PatientLinkId))
            //    {
            //        pm = PatientLinkService.Instance.GetObjById(model.PatientLinkId);

            //    }
            //    if (DataManager.Instance.CurrentControl is XuanZeShouShuCtrl)
            //    {
            //        if (pm == null) return;
            //        MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
            //        Dispatcher.Invoke(delegate
            //        {
            //            XuanZeShouShuCtrlViewModel.Instance.UdpRef(pm);
            //            MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
            //        });
            //    }
            //    else if (DataManager.Instance.CurrentControl is SecheduleMainCtrl)
            //    {
            //        if (pm == null) return;
            //        MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
            //        Dispatcher.Invoke(delegate
            //        {
            //            SecheduleMainCtrlViewModel.Instance.UdpRef(pm);
            //            MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
            //        });
            //    }
            //    else if (DataManager.Instance.CurrentControl is BasePrintControl)
            //    {
            //        //if ((pm != null && DataManager.Instance.CurrentPatientLink != null && DataManager.Instance.CurrentPatientLink.Id.Equals(pm.Id)) ||
            //        //        (pm == null && !string.IsNullOrEmpty(model.PatientLinkId) && DataManager.Instance.CurrentPatientLink != null && DataManager.Instance.CurrentPatientLink.Id.Equals(model.PatientLinkId)))
            //        //{
            //        //    UpdatePatientLink(model, pm);
            //        //}
            //    }

            //    if (pm != null && (DataManager.Instance.PatientLinkCache.ContainsKey(pm.Id)))
            //    {
            //        DataManager.Instance.PatientLinkCache.Remove(pm.Id);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    isTip = false;
            //    LogHelper.Error(this.GetType(), ex);
            //}
        }

        private void UpdatePatientLink(AnesSystemModifyInfoModel model, PatientLinkModel pm)
        {
            AccountModel account = DataManager.Instance.GetAccountByID(model.AccountID);
            string msg = string.Format("当前病人（{0}）信息已经被{1}号手术间工号为{2}的{3}医生修改，是否进行更新？",
                                    DataManager.Instance.CurrentPatientLink.Patient.Brxm, model.RoomID, account.WorkID, account.TrueName);
            isTip = true;
            Dispatcher.Invoke(delegate
            {
                MessageBoxCommon.ShowDialog(msg, 0);
            });

            if (DataManager.Instance.CurrentControl is BaseTableControl)
            {
                DataManager.Instance.IsNotNeedSaveData = true;
                UdpMangager.Instance.IsNeedSendMessage = false;
                DataManager.Instance.CurrentPatientLink = pm;
                MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
                Task.Factory.StartNew(delegate
                {
                    Dispatcher.Invoke(delegate
                        {
                            (DataManager.Instance.CurrentControl as BaseTableControl).Refesh();
                            MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                            isTip = false;
                        }, System.Windows.Threading.DispatcherPriority.Background);

                });
            }
        }

        #endregion


    }
}
